<template>
  <div class="chat-message-item">
    <!-- 系统消息：居中显示 -->
    <div class="message-tip-container" v-if="
      msgInfo.type == $enums.MESSAGE_TYPE.TIP_TEXT ||
      msgInfo.type == $enums.MESSAGE_TYPE.TIP_TIME
    ">
      <div class="message-tip">
        {{
          msgInfo.type == $enums.MESSAGE_TYPE.TIP_TEXT
            ? msgInfo.content
            : $date.toTimeText(msgInfo.sendTime)
        }}
      </div>
    </div>

    <!-- AI消息：使用专门的AI消息框 -->
    <div v-if="isNormal && isAIMessage" class="ai-message-wrapper">
      <AIMessageBox
        :content="msgInfo.content || displayAIContent"
        :thinking-content="displayAIThinkingContent"
        :response-content="displayAIContent"
        :is-streaming="msgInfo.isStreaming"
        :stream-type="msgInfo.streamType"
        :send-time="msgInfo.sendTime"
        :is-complete="!msgInfo.isStreaming"
        @content-updated="$emit('scroll-to-bottom')"
      />
    </div>

    <!-- 用户消息：左右两侧显示 -->
    <div class="message-container" v-else-if="isNormal && !isAIMessage" :class="{ 'message-mine': mine }">
      <!-- 头像容器 -->
      <div class="avatar-wrapper">
        <div class="avatar-container">
          <head-image :name="showName" :size="38" :url="headImage" :id="msgInfo.sendId"></head-image>
        </div>
      </div>

      <!-- 消息内容容器 -->
      <div class="message-content">
        <!-- 消息头部信息 -->
        <div v-show="mode == 1 && msgInfo.groupId && !msgInfo.selfSend" class="message-header">
          <span class="sender-name">{{ showName }}</span>
        </div>
        <div v-show="mode == 2" class="message-header">
          <span class="sender-name">{{ showName }}</span>
          <span class="send-time">{{ $date.toTimeText(msgInfo.sendTime) }}</span>
        </div>

        <!-- 消息主体 -->
        <div class="message-body" @contextmenu.prevent="showRightMenu($event)">
          <!-- 发送失败图标 -->
          <span title="发送失败" v-show="loadFail" @click="onSendFail" class="send-fail-icon fas fa-exclamation-triangle"></span>

          <div ref="chatMsgBox">
            <!-- 普通文本消息 -->
            <span v-if="msgInfo.type == $enums.MESSAGE_TYPE.TEXT"
                  class="message-text"
                  v-html="renderedText"></span>
            <div class="message-image" v-if="msgInfo.type == $enums.MESSAGE_TYPE.IMAGE">
              <div class="img-load-box" v-loading="loading" element-loading-text="上传中.."
                element-loading-background="rgba(0, 0, 0, 0.4)">
                <img class="send-image" :src="JSON.parse(msgInfo.content).thumbUrl" @click="showFullImageBox()"
                  loading="lazy" />
              </div>
            </div>
            <div class="message-file" v-if="msgInfo.type == $enums.MESSAGE_TYPE.FILE">
              <div class="chat-file-box" v-loading="loading">
                <div class="chat-file-info">
                  <el-link class="chat-file-name" :underline="true" target="_blank" type="primary" :href="data.url"
                    :download="data.name">{{ data.name }}</el-link>
                  <div class="chat-file-size">{{ fileSize }}</div>
                </div>
                <div class="chat-file-icon">
                  <span type="primary" class="el-icon-document"></span>
                </div>
              </div>

            </div>
            <!-- 混合消息（图片+文字） - 重构版本 -->
            <div class="mixed-message-container" v-if="msgInfo.type == $enums.MESSAGE_TYPE.MIXED">
              <div class="mixed-content-wrapper" :class="{ 'is-self': msgInfo.selfSend }"
                   v-loading="loading" element-loading-text="上传中..."
                   element-loading-background="rgba(0, 0, 0, 0.4)">
                <!-- 按照用户输入顺序显示内容 -->
                <div v-for="(item, index) in mixedData.items" :key="index" class="mixed-content-item">
                  <!-- 文字内容 -->
                  <div v-if="item.type === 'text'" class="mixed-text-content" v-html="formatMixedText(item.content)"></div>
                  <!-- 图片内容 -->
                  <div v-else-if="item.type === 'image'" class="mixed-image-container">
                    <img
                      :src="item.thumbUrl || item.content"
                      :alt="item.name || '图片'"
                      class="mixed-image-element"
                      loading="lazy"
                      @click="showMixedImage(item, index)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="message-voice" v-if="msgInfo.type == $enums.MESSAGE_TYPE.AUDIO" @click="onPlayVoice()">
            <audio controls :src="JSON.parse(msgInfo.content).url"></audio>
          </div>
          <div class="chat-action message-text" v-if="isAction">
            <div class="action-content" @click="onActionClick">
              <div class="action-icon">
                <i v-if="msgInfo.type == $enums.MESSAGE_TYPE.ACT_RT_VOICE" class="fas fa-phone"
                  title="语音通话 - 点击重新呼叫"></i>
                <i v-if="msgInfo.type == $enums.MESSAGE_TYPE.ACT_RT_VIDEO" class="fas fa-video"
                  title="视频通话 - 点击重新呼叫"></i>
              </div>
              <span class="action-text">{{ msgInfo.content }}</span>
              <div class="action-hint">
                <i class="fas fa-redo-alt"></i>
                <span>点击重新呼叫</span>
              </div>
            </div>
          </div>
          <!-- 消息状态 -->
          <div class="message-status" v-if="!isAction">
            <span class="status-read" v-show="msgInfo.selfSend &&
              !msgInfo.groupId &&
              currentMessageStatus == $enums.MESSAGE_STATUS.READED
              ">已读</span>
            <span class="status-unread" v-show="msgInfo.selfSend &&
              !msgInfo.groupId &&
              currentMessageStatus != $enums.MESSAGE_STATUS.READED
              ">未读</span>
          </div>

          <!-- 群聊回执 -->
          <div class="message-receipt" v-show="msgInfo.receipt" @click="onShowReadedBox">
            <span v-if="msgInfo.receiptOk" class="icon iconfont icon-ok" title="全体已读"></span>
            <span v-else>{{ msgInfo.readedCount }}人已读</span>
          </div>
        </div>
      </div>
    </div>
    <right-menu ref="rightMenu" @select="onSelectMenu"></right-menu>
    <chat-group-readed ref="chatGroupReadedBox" :msgInfo="msgInfo" :groupMembers="groupMembers"></chat-group-readed>
  </div>
</template>

<script>
import HeadImage from "../common/HeadImage.vue";
import RightMenu from "../common/RightMenu.vue";
import ChatGroupReaded from "./ChatGroupReaded.vue";
import AIMessageBox from "./AIMessageBox.vue";
// 导入Markdown和代码高亮工具
import { renderContent, applyHighlighting } from "@/utils/highlight.js";
export default {
  name: "messageItem",
  components: {
    HeadImage,
    RightMenu,
    ChatGroupReaded,
    AIMessageBox,
  },
  props: {
    mode: {
      type: Number,
      default: 1,
    },
    mine: {
      type: Boolean,
      required: true,
    },
    headImage: {
      type: String,
      required: true,
    },
    showName: {
      type: String,
      required: true,
    },
    msgInfo: {
      type: Object,
      required: true,
    },
    groupMembers: {
      type: Array,
    },
    menu: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      audioPlayState: "STOP",
      lastActionClickTime: 0, // 上次点击重新拨打的时间
      actionClickThrottle: 2000, // 2秒内防止重复点击重新拨打
      currentMessageStatus: this.msgInfo.status, // 响应式的消息状态，用于实时更新UI
    };
  },
  mounted() {
    // 组件挂载后应用代码高亮
    this.applyCodeHighlighting();

    // 监听消息状态更新事件
    this.$eventBus.$on('message-status-update', this.handleMessageStatusUpdate);
  },

  beforeDestroy() {
    // 组件销毁前移除事件监听器
    this.$eventBus.$off('message-status-update', this.handleMessageStatusUpdate);
  },

  watch: {
    // 监听msgInfo.status的变化，确保状态同步
    'msgInfo.status': {
      handler(newStatus) {
        if (this.currentMessageStatus !== newStatus) {
          this.currentMessageStatus = newStatus;
          console.log('msgInfo.status变化，同步更新currentMessageStatus:', newStatus);
        }
      },
      immediate: true
    }
  },
  updated() {
    // 组件更新后重新应用代码高亮（用于流式更新的消息）
    this.applyCodeHighlighting();
  },
  methods: {
    // 应用代码高亮
    applyCodeHighlighting() {
      // 只对AI消息应用代码高亮
      if (this.msgInfo.sendId === this.$enums.AI_ASSISTANT.XIAO_ASSISTANT_ID) {
        this.$nextTick(() => {
          applyHighlighting('.message-text');
        });
      }
    },

    /**
     * 处理消息状态更新事件
     * @param {Object} data - 事件数据 {messageId, status}
     */
    handleMessageStatusUpdate(data) {
      try {
        // 检查是否是当前消息
        if (data.messageId === this.msgInfo.id) {
          console.log('收到消息状态更新事件，消息ID:', data.messageId, '新状态:', data.status, '消息内容:', this.msgInfo.content);

          // 更新本地响应式状态
          this.currentMessageStatus = data.status;

          // 同时更新原始msgInfo对象的状态（保持数据一致性）
          this.$set(this.msgInfo, 'status', data.status);

          console.log('消息状态已更新为:', data.status === this.$enums.MESSAGE_STATUS.READED ? '已读' : '未读');
        }
      } catch (error) {
        console.error('处理消息状态更新事件失败:', error);
      }
    },

    onSendFail() {
      this.$message.error(
        "该文件已发送失败，目前不支持自动重新发送，建议手动重新发送"
      );
    },
    showFullImageBox() {
      let imageUrl = JSON.parse(this.msgInfo.content).originUrl;
      if (imageUrl) {
        this.$eventBus.$emit("openFullImage", imageUrl);
      }
    },
    onPlayVoice() {
      if (!this.audio) {
        this.audio = new Audio();
      }
      this.audio.src = JSON.parse(this.msgInfo.content).url;
      this.audio.play();
      this.onPlayVoice = "RUNNING";
    },
    showRightMenu(e) {
      this.$refs.rightMenu.open(e, this.menuItems);
    },
    onSelectMenu(item) {
      // 处理复制功能
      if (item.key === 'COPY') {
        this.copyMessageText();
        return;
      }

      this.$emit(item.key.toLowerCase(), this.msgInfo);
    },

    // 复制消息文本内容 - 简化版本
    copyMessageText() {
      try {
        let textContent = "";

        // 根据消息类型获取文本内容
        if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.TEXT) {
          textContent = this.msgInfo.content;
        } else if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.MIXED) {
          // 混合消息只复制文字部分
          textContent = this.mixedData.items
            .filter(item => item.type === 'text')
            .map(item => item.content)
            .join('\n') || "";
        }

        // 去除HTML标签
        if (textContent.includes('<')) {
          const tempDiv = document.createElement('div');
          tempDiv.innerHTML = textContent;
          textContent = tempDiv.textContent || tempDiv.innerText || '';
        }

        // 使用现代剪贴板API
        if (navigator.clipboard) {
          navigator.clipboard.writeText(textContent).then(() => {
            this.$message.success('消息已复制');
          }).catch(() => {
            this.$message.error('复制失败');
          });
        } else {
          this.$message.error('浏览器不支持复制功能');
        }
      } catch (error) {
        this.$message.error('复制失败');
      }
    },
    onShowReadedBox() {
      let rect = this.$refs.chatMsgBox.getBoundingClientRect();
      this.$refs.chatGroupReadedBox.open(rect);
    },

    // 处理通话操作点击事件
    onActionClick() {
      // 防抖机制：防止用户快速点击重新拨打
      const currentTime = Date.now();
      if (currentTime - this.lastActionClickTime < this.actionClickThrottle) {
        console.log("重新拨打请求过于频繁，已忽略");
        this.$message.warning("请勿频繁重新拨打");
        return;
      }
      this.lastActionClickTime = currentTime;

      if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VOICE) {
        // 触发语音通话
        console.log("点击重新发起语音通话");
        this.$emit('voice-call', this.msgInfo);
      } else if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.ACT_RT_VIDEO) {
        // 触发视频通话
        console.log("点击重新发起视频通话");
        this.$emit('video-call', this.msgInfo);
      }
    },
    // 格式化混合消息中的文字内容
    formatMixedText(text) {
      if (!text) return "";
      // 处理@用户
      let result = text.replace(/@([^@\s]+)/g, '<span class="at-user">@$1</span>');
      // 处理换行
      result = result.replace(/\n/g, '<br>');
      // 处理URL链接
      let color = this.msgInfo.selfSend ? "white" : "";
      result = this.$url.replaceURLWithHTMLLinks(result, color);
      // 处理表情包转换
      result = this.$emo.transform(result, "emoji-normal");
      return result;
    },
    // 获取图片网格的CSS类
    getImageGridClass(imageCount) {
      if (imageCount === 1) return "grid-single";
      if (imageCount === 2) return "grid-double";
      if (imageCount === 3) return "grid-triple";
      if (imageCount === 4) return "grid-quad";
      return "grid-multiple";
    },
    // 显示混合消息中的图片
    showMixedImage(image) {
      // 使用现有的图片预览机制
      if (image.originUrl) {
        this.$eventBus.$emit("openFullImage", image.originUrl);
      } else if (image.content) {
        this.$eventBus.$emit("openFullImage", image.content);
      }
    },
    /**
     * 从完整的AI消息内容中解析出回复内容部分
     */
    parseResponseContent(fullContent) {
      if (!fullContent) return ''

      // 先处理群聊@用户名格式，移除开头的@用户名部分
      let content = this.removeAtUserPrefix(fullContent)

      // 查找 "🤖 *回复*" 标记
      const responseMarker = '🤖 *回复*'
      const responseIndex = content.indexOf(responseMarker)

      if (responseIndex !== -1) {
        // 提取回复内容（去掉标记后的内容）
        return content.substring(responseIndex + responseMarker.length).trim()
      }

      // 如果没有找到标记，返回原内容
      return content
    },

    /**
     * 从完整的AI消息内容中解析出思考过程部分
     */
    parseThinkingContent(fullContent) {
      if (!fullContent) return ''

      // 先处理群聊@用户名格式，移除开头的@用户名部分
      let content = this.removeAtUserPrefix(fullContent)

      // 查找思考过程的开始和结束标记
      const thinkingStart = content.indexOf('📝 *思考过程')
      const thinkingEnd = content.indexOf('🤖 *回复*')

      if (thinkingStart !== -1 && thinkingEnd !== -1) {
        // 提取思考过程部分
        let thinkingSection = content.substring(thinkingStart, thinkingEnd).trim()

        // 移除开头的标题行（如：📝 *思考过程 (2.3秒)*）
        const firstNewlineIndex = thinkingSection.indexOf('\n')
        if (firstNewlineIndex !== -1) {
          thinkingSection = thinkingSection.substring(firstNewlineIndex + 1).trim()
        }

        // 如果内容被```包围，提取其中的内容；否则返回完整内容
        const codeBlockStart = thinkingSection.indexOf('```')
        const codeBlockEnd = thinkingSection.lastIndexOf('```')

        if (codeBlockStart !== -1 && codeBlockEnd !== -1 && codeBlockStart !== codeBlockEnd) {
          // 提取```之间的内容，保留换行和格式
          let codeContent = thinkingSection.substring(codeBlockStart + 3, codeBlockEnd)
          // 移除开头可能的语言标识（如：```javascript 或 ```）
          const firstLine = codeContent.split('\n')[0]
          if (firstLine.trim() && !firstLine.includes(' ') && firstLine.length < 20) {
            codeContent = codeContent.substring(firstLine.length + 1)
          }
          return codeContent.trim()
        } else {
          // 没有代码块包围，返回完整的思考内容
          return thinkingSection
        }
      }

      return ''
    },

    /**
     * 移除群聊AI消息开头的@用户名部分
     */
    removeAtUserPrefix(content) {
      if (!content) return ''

      // 检查是否以@开头（群聊AI回复格式）
      if (content.startsWith('@')) {
        // 查找第一个换行符，移除@用户名部分
        const firstNewlineIndex = content.indexOf('\n')
        if (firstNewlineIndex !== -1) {
          // 移除@用户名和后面的空行，保留实际内容
          let remainingContent = content.substring(firstNewlineIndex + 1)
          // 移除开头的空行
          while (remainingContent.startsWith('\n')) {
            remainingContent = remainingContent.substring(1)
          }
          return remainingContent
        }
      }

      // 如果不是群聊格式，直接返回原内容
      return content
    }
  },
  computed: {
    loading() {
      return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "loading";
    },
    loadFail() {
      return this.msgInfo.loadStatus && this.msgInfo.loadStatus === "fail";
    },
    data() {
      return JSON.parse(this.msgInfo.content);
    },
    // 混合消息数据
    mixedData() {
      if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.MIXED) {
        try {
          return JSON.parse(this.msgInfo.content);
        } catch (e) {
          console.error("解析混合消息内容失败：", e);
          return { items: [] };
        }
      }
      return { items: [] };
    },
    fileSize() {
      let size = this.data.size;
      if (size > 1024 * 1024) {
        return Math.round(size / 1024 / 1024) + "M";
      }
      if (size > 1024) {
        return Math.round(size / 1024) + "KB";
      }
      return size + "B";
    },
    menuItems() {
      let items = [];

      // 复制消息（文本消息和混合消息）
      if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.TEXT) {
        items.push({
          key: "COPY",
          name: "复制文本",
          icon: "fas fa-copy",
        });
      } else if (this.msgInfo.type == this.$enums.MESSAGE_TYPE.MIXED &&
                 this.mixedData.items &&
                 this.mixedData.items.some(item => item.type === 'text')) {
        items.push({
          key: "COPY",
          name: "复制文本",
          icon: "fas fa-copy",
        });
      }

      // 撤回消息（仅自己发送的消息且在时间限制内）
      if (this.msgInfo.selfSend && this.msgInfo.id > 0) {
        const now = Date.now();
        const sendTime = new Date(this.msgInfo.sendTime).getTime();
        const timeDiff = now - sendTime;
        // 5分钟内可以撤回
        if (timeDiff < 5 * 60 * 1000) {
          items.push({
            key: "RECALL",
            name: "撤回消息",
            icon: "fas fa-undo",
          });
        }
      }

      // 删除消息（本地删除）
      items.push({
        key: "DELETE",
        name: "删除消息",
        icon: "fas fa-trash-alt",
        color: "#F56C6C"
      });

      return items;
    },
    isAction() {
      return this.$msgType.isAction(this.msgInfo.type);
    },
    isNormal() {
      const type = this.msgInfo.type;
      return this.$msgType.isNormal(type) || this.$msgType.isAction(type);
    },
    htmlText() {
      let color = this.msgInfo.selfSend ? "white" : "";
      let text = this.$url.replaceURLWithHTMLLinks(this.msgInfo.content, color);
      return this.$emo.transform(text, "emoji-normal");
    },
    // 检查是否是AI助手的消息
    isAIMessage() {
      return this.msgInfo.sendId === this.$enums.AI_ASSISTANT.XIAO_ASSISTANT_ID ||
             this.msgInfo.isAIMessage ||
             this.msgInfo.isAIStreamMessage;
    },

    // AI消息显示内容 - 统一处理不同来源的AI消息格式
    displayAIContent() {
      // 如果有单独的回复内容，优先使用（SSE流式传输的消息）
      if (this.msgInfo.responseContent) {
        return this.msgInfo.responseContent;
      }

      // 如果是从数据库加载的完整格式消息，需要解析
      if (this.msgInfo.content && this.msgInfo.content.includes('🤖 *回复*')) {
        return this.parseResponseContent(this.msgInfo.content);
      }

      // 否则使用原始内容（但需要移除@用户名部分用于内容显示）
      return this.removeAtUserPrefix(this.msgInfo.content || '');
    },

    /**
     * 显示的@用户名部分（仅用于群聊AI消息）
     */
    displayAtUserName() {
      if (!this.msgInfo.content || !this.msgInfo.content.startsWith('@')) {
        return '';
      }

      // 提取@用户名部分
      const firstNewlineIndex = this.msgInfo.content.indexOf('\n');
      if (firstNewlineIndex !== -1) {
        return this.msgInfo.content.substring(0, firstNewlineIndex).trim();
      }

      return '';
    },

    // AI消息思考内容 - 统一处理不同来源的AI消息格式
    displayAIThinkingContent() {
      // 如果有单独的思考内容，优先使用（SSE流式传输的消息）
      if (this.msgInfo.thinkingContent) {
        return this.msgInfo.thinkingContent;
      }

      // 如果是从数据库加载的完整格式消息，需要解析
      if (this.msgInfo.content && this.msgInfo.content.includes('📝 *思考过程')) {
        return this.parseThinkingContent(this.msgInfo.content);
      }

      // 没有思考内容
      return '';
    },
    // 新增：支持Markdown渲染的文本内容
    renderedText() {
      if (this.isAIMessage) {
        // AI消息使用Markdown渲染
        const options = {
          markdown: true,
          codeHighlight: true,
          linkNewWindow: true,
          purifyHtml: true,
          forceMarkdown: true // 强制使用Markdown渲染
        };
        return renderContent(this.msgInfo.content, options);
      } else {
        // 普通用户消息使用原有逻辑
        return this.htmlText;
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.chat-message-item {
  width: 100%;
  margin-bottom: 16px;

  // AI消息框样式
  .ai-message-wrapper {
    width: 100%;
    padding: 8px 16px;
    display: flex;
    justify-content: flex-start;

    // 确保AI消息框不超出容器
    :deep(.ai-message-container) {
      max-width: 100%;
      width: 100%;
      box-sizing: border-box;
    }
  }

  // 系统消息容器：居中显示
  .message-tip-container {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 12px 0;

    .message-tip {
      background: var(--im-bg-hover);
      color: var(--im-text-color-secondary);
      font-size: var(--im-font-size-sm);
      padding: 6px 12px;
      border-radius: 12px;
      max-width: 300px;
      text-align: center;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
  }

  // === 用户消息容器：重构版本 ===
  .message-container {
    width: 100%;
    display: flex;
    margin-bottom: 16px;
    padding: 0 20px; // 左右留出足够空间
    min-height: 50px;
    align-items: flex-start;
    position: relative;

    // === 头像容器 ===
    .avatar-wrapper {
      flex-shrink: 0;
      width: 38px;
      height: 38px;
      position: relative;
      z-index: 10;

      .avatar-container {
        width: 38px;
        height: 38px;
        border-radius: 50%;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        background: #f5f5f5;
        position: relative;

        // 确保头像组件完全填充容器
        :deep(.head-image-container) {
          width: 100% !important;
          height: 100% !important;
          border-radius: 50% !important;
          overflow: hidden !important;
        }

        :deep(img) {
          width: 100% !important;
          height: 100% !important;
          object-fit: cover !important;
          display: block !important;
          border-radius: 50% !important;
          margin: 0 !important;
          padding: 0 !important;
          border: none !important;
        }
      }
    }

    // === 消息内容容器 ===
    .message-content {
      flex: 1;
      min-width: 0; // 允许内容收缩
      display: flex;
      flex-direction: column;

      .message-header {
        margin-bottom: 4px;
        font-size: 12px;
        color: var(--im-text-color-secondary);
        line-height: 1.4;

        .sender-name {
          font-weight: 500;
          margin-right: 8px;
        }

        .send-time {
          opacity: 0.7;
        }
      }

      .message-body {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        // AI流式消息样式
        .ai-streaming-message {
          display: inline-block;
          width: 100%;
        }

        // 通用消息样式
        .message-text,
        .message-image,
        .message-file,
        .message-voice,
        .chat-action {
          margin-bottom: 4px;
        }
      }
    }

    // === 他人消息：左侧布局 ===
    &:not(.message-mine) {
      flex-direction: row;

      .avatar-wrapper {
        margin-right: 12px;
      }

      .message-content {
        .message-header {
          text-align: left;
        }

        .message-body {
          align-items: flex-start;
        }
      }

      .message-text {
        background: var(--im-bg-secondary);
        color: var(--im-text-color-primary);
        border-radius: 18px 18px 18px 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        padding: 10px 16px;
        max-width: 400px;
        word-break: break-word;
        line-height: 1.4;
        position: relative;
        display: inline-block;
        transition: all 0.2s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
          transform: translateY(-1px);
        }

        &:after {
          content: '';
          position: absolute;
          left: -6px;
          bottom: 8px;
          border: solid transparent;
          border-color: transparent var(--im-bg-secondary) transparent transparent;
          border-width: 6px 6px 6px 0;
        }
      }
    }

    // === 自己的消息：右侧布局 ===
    &.message-mine {
      flex-direction: row-reverse;

      .avatar-wrapper {
        margin-left: 12px;
        margin-right: 0;
      }

      .message-content {
        .message-header {
          text-align: right;
        }

        .message-body {
          align-items: flex-end;

          // 右边消息的通用样式
          .message-text,
          .message-image,
          .message-file,
          .message-voice,
          .chat-action {
            margin-bottom: 4px;
          }
        }
      }

      .message-text {
        background: linear-gradient(135deg,
            var(--im-color-primary) 0%,
            var(--im-color-primary-light-2) 100%);
        color: white;
        border-radius: 18px 18px 4px 18px;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.25);
        padding: 10px 16px;
        max-width: 400px;
        word-break: break-word;
        line-height: 1.4;
        position: relative;
        display: inline-block;
        transition: all 0.2s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.35);
          transform: translateY(-1px);
        }

        &:after {
          content: '';
          position: absolute;
          right: -6px;
          left: auto;
          bottom: 8px;
          border: solid transparent;
          border-color: transparent transparent transparent var(--im-color-primary);
          border-width: 6px 0 6px 6px;
        }
      }
    }

    // === 消息状态样式 ===
    .message-status {
      margin-top: 4px;
      font-size: 11px;
      color: var(--im-text-color-placeholder);
      text-align: left;

      .status-read {
        color: var(--im-color-success);
      }

      .status-unread {
        color: var(--im-text-color-secondary);
      }
    }

    .message-receipt {
      margin-top: 4px;
      font-size: 11px;
      color: var(--im-text-color-secondary);
      cursor: pointer;
      text-align: left;

      &:hover {
        color: var(--im-color-primary);
      }

      .icon {
        color: var(--im-color-success);
      }
    }

    // === 自己消息的状态样式 ===
    &.message-mine {

      .message-status,
      .message-receipt {
        text-align: right;
      }
    }

    // === 其他消息类型样式 ===
    .message-image {
      .img-load-box {
        border-radius: 8px;
        overflow: hidden;
        max-width: 200px;
        position: relative;

        .send-image {
          width: 100%;
          height: auto;
          display: block;
          cursor: pointer;
          transition: transform 0.2s ease;

          &:hover {
            transform: scale(1.02);
          }
        }
      }

      .send-fail-icon {
        position: absolute;
        left: -25px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--im-color-danger);
        cursor: pointer;
        font-size: 16px;
        z-index: 10;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        padding: 2px;
      }
    }

    .message-file {
      .chat-file-box {
        display: flex;
        align-items: center;
        background: var(--im-bg-tertiary);
        border-radius: 8px;
        padding: 12px;
        max-width: 300px;
        border: 1px solid var(--im-border-color);

        .chat-file-info {
          flex: 1;
          margin-right: 12px;

          .chat-file-name {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
          }

          .chat-file-size {
            font-size: 12px;
            color: var(--im-text-color-secondary);
          }
        }

        .chat-file-icon {
          font-size: 24px;
          color: var(--im-color-primary);
        }
      }
    }

    .message-voice {
      audio {
        max-width: 200px;
      }
    }

    // 混合消息样式 - 全新重构版本
    .mixed-message-container {
      display: flex;
      width: 100%;

      .mixed-content-wrapper {
        position: relative;
        max-width: 400px;
        min-width: 200px;
        padding: 16px;
        border-radius: 16px;
        word-break: break-word;
        line-height: 1.4;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        margin: 4px 0;
        box-sizing: border-box;
        overflow: hidden;

        // 接收消息样式（默认）
        background: var(--im-bg-tertiary);
        color: var(--im-text-color-primary);
        border: 1px solid var(--im-border-color-light);
        border-bottom-left-radius: 8px;
        margin-right: auto;

        // 自发送消息样式
        &.is-self {
          background: linear-gradient(135deg, var(--im-color-primary), var(--im-color-primary-light-1));
          color: white;
          border: none;
          border-bottom-left-radius: 16px;
          border-bottom-right-radius: 8px;
          margin-left: auto;
          margin-right: 0;

          .mixed-text-content {
            color: rgba(255, 255, 255, 0.95);

            // 自发送消息中的@用户样式
            .at-user {
              color: rgba(255, 255, 255, 0.9);
              background: rgba(255, 255, 255, 0.15);
              padding: 2px 6px;
              border-radius: 4px;
              font-weight: 500;
            }
          }
        }

        // 接收消息中的@用户样式
        .mixed-text-content {
          .at-user {
            color: var(--im-color-primary);
            background: var(--im-color-primary-light-9);
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 500;
          }
        }

        .mixed-content-item {
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }

          .mixed-text-content {
            line-height: 1.5;
            word-wrap: break-word;
            font-size: 14px;
            margin: 0;
            white-space: pre-wrap;

            // 表情包样式
            .emoji {
              font-size: 18px;
              vertical-align: middle;
              margin: 0 2px;
            }

            // 链接样式
            a {
              color: inherit;
              text-decoration: underline;
              opacity: 0.8;

              &:hover {
                opacity: 1;
              }
            }
          }

          .mixed-image-container {
            display: block;
            max-width: 280px;
            border-radius: 12px;
            overflow: hidden;
            cursor: pointer;
            margin: 8px 0;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;

            &:hover {
              box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
              transform: translateY(-1px);
            }

            .mixed-image-element {
              width: 100%;
              height: auto;
              max-height: 300px;
              object-fit: cover;
              display: block;
              transition: transform 0.3s ease;

              &:hover {
                transform: scale(1.02);
              }
            }
          }
        }

        // 响应式设计
        @media (max-width: 768px) {
          max-width: 320px;
          padding: 12px;

          .mixed-content-item {
            .mixed-image-container {
              max-width: 240px;

              .mixed-image-element {
                max-height: 240px;
              }
            }
          }
        }

        @media (max-width: 480px) {
          max-width: 280px;
          padding: 10px;

          .mixed-content-item {
            margin-bottom: 10px;

            .mixed-text-content {
              font-size: 13px;
            }

            .mixed-image-container {
              max-width: 200px;
              margin: 6px 0;

              .mixed-image-element {
                max-height: 200px;
              }
            }
          }
        }
      }
    }
    }

    .chat-action {
      max-width: 280px;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
        transform: translateY(-1px);
      }

      .action-content {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        cursor: pointer;
        position: relative;
        transition: all 0.3s ease;

        &:hover {
          background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);

          .action-hint {
            opacity: 1;
            transform: translateX(0);
          }
        }

        .action-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 36px;
          height: 36px;
          border-radius: 50%;
          margin-right: 12px;
          flex-shrink: 0;
          transition: all 0.3s ease;

          i {
            font-size: 16px;
            transition: all 0.3s ease;
          }

          // 语音通话图标样式
          &:has(.fa-phone) {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);

            &:hover {
              background: linear-gradient(135deg, #20c997 0%, #17a2b8 100%);
              transform: scale(1.1);
            }
          }

          // 视频通话图标样式
          &:has(.fa-video) {
            background: linear-gradient(135deg, #007bff 0%, #6610f2 100%);
            color: white;
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);

            &:hover {
              background: linear-gradient(135deg, #6610f2 0%, #e83e8c 100%);
              transform: scale(1.1);
            }
          }
        }

        .action-text {
          flex: 1;
          font-size: 14px;
          font-weight: 500;
          color: var(--im-text-color-primary);
          line-height: 1.4;
        }

        .action-hint {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 12px;
          color: var(--im-text-color-secondary);
          opacity: 0;
          transform: translateX(10px);
          transition: all 0.3s ease;

          i {
            font-size: 10px;
          }

          span {
            white-space: nowrap;
          }
        }
      }
    }
  }


// === 深色模式适配 ===
:root[data-theme='dark'] {
  .chat-message-item {

    // 深色模式下的通话消息样式
    .chat-action {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
      }

      .action-content {
        // 深色模式下的背景渐变
        background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
        border: 1px solid rgba(255, 255, 255, 0.1);

        &:hover {
          background: linear-gradient(135deg, #34495e 0%, #3c5a78 100%);
          border-color: rgba(255, 255, 255, 0.15);
        }

        .action-icon {
          // 深色模式下的图标样式保持不变，因为已经有足够的对比度

          // 语音通话图标 - 在深色模式下使用更亮的绿色
          &:has(.fa-phone) {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
            box-shadow: 0 2px 8px rgba(39, 174, 96, 0.4);

            &:hover {
              background: linear-gradient(135deg, #2ecc71 0%, #58d68d 100%);
              box-shadow: 0 3px 12px rgba(39, 174, 96, 0.5);
            }
          }

          // 视频通话图标 - 在深色模式下使用更亮的蓝色
          &:has(.fa-video) {
            background: linear-gradient(135deg, #3498db 0%, #5dade2 100%);
            box-shadow: 0 2px 8px rgba(52, 152, 219, 0.4);

            &:hover {
              background: linear-gradient(135deg, #5dade2 0%, #85c1e9 100%);
              box-shadow: 0 3px 12px rgba(52, 152, 219, 0.5);
            }
          }
        }

        .action-text {
          color: #ecf0f1; // 深色模式下的文字颜色
        }

        .action-hint {
          color: #bdc3c7; // 深色模式下的提示文字颜色

          i {
            color: #85c1e9; // 深色模式下的提示图标颜色
          }
        }
      }
    }

    // 深色模式下的系统消息
    .message-tip-container {
      .message-tip {
        background: rgba(255, 255, 255, 0.1);
        color: #bdc3c7;
        border: 1px solid rgba(255, 255, 255, 0.05);
      }
    }

    // 深色模式下的消息气泡优化
    .message-container {

      // 他人消息气泡
      &:not(.message-mine) {
        .message-text {
          background: #34495e;
          color: #ecf0f1;
          border: 1px solid rgba(255, 255, 255, 0.1);

          &:after {
            border-color: transparent #34495e transparent transparent;
          }
        }
      }

      // 自己的消息气泡保持原有的蓝色渐变，在深色模式下更加突出
      &.message-mine {
        .message-text {
          background: linear-gradient(135deg, var(--im-color-primary) 0%, #5dade2 100%);
          box-shadow: 0 2px 8px rgba(52, 152, 219, 0.3);

          &:hover {
            box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
          }

          &:after {
            border-color: transparent transparent transparent var(--im-color-primary);
          }
        }
      }
    }
  }
}

// 旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// AI消息的Markdown和代码高亮样式
.message-text {
  // 代码块样式
  :deep(pre) {
    background-color: #f6f8fa;
    border-radius: 6px;
    padding: 16px;
    margin: 8px 0;
    overflow-x: auto;
    position: relative;

    code {
      background: none;
      padding: 0;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 14px;
      line-height: 1.45;
    }
  }

  // 行内代码样式
  :deep(code.inline-code) {
    background-color: rgba(175, 184, 193, 0.2);
    padding: 2px 4px;
    border-radius: 3px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: 85%;
  }

  // 复制按钮样式
  :deep(.code-copy-btn) {
    position: absolute;
    top: 8px;
    right: 8px;
    background: rgba(255, 255, 255, 0.8);
    border: 1px solid #d0d7de;
    border-radius: 4px;
    padding: 4px 8px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;

    &:hover {
      background: rgba(255, 255, 255, 0.9);
    }

    &.success {
      background: #28a745;
      color: white;
      border-color: #28a745;
    }

    &.error {
      background: #dc3545;
      color: white;
      border-color: #dc3545;
    }
  }

  // Markdown其他元素样式
  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
    margin: 16px 0 8px 0;
    font-weight: 600;
  }

  :deep(ul), :deep(ol) {
    margin: 8px 0;
    padding-left: 20px;
  }

  :deep(blockquote) {
    border-left: 4px solid #d0d7de;
    padding-left: 16px;
    margin: 8px 0;
    color: #656d76;
  }

  :deep(table) {
    border-collapse: collapse;
    margin: 8px 0;

    th, td {
      border: 1px solid #d0d7de;
      padding: 6px 13px;
    }

    th {
      background-color: #f6f8fa;
      font-weight: 600;
    }
  }
}
</style>
